import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select,
  Button, DatePicker, Table, Modal, Menu, Dropdown, Icon } from 'antd';
import styles from './UserManagement.less';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import AddManager from './AddManager';
import ShowManagerInfo from './ShowManagerInfo';
import globalConstant from '../../utils/globalConstant';


const FormItem = Form.Item;
const { Option } = Select;


@connect(({ sysUser, loading }) => ({
  sysUser,
  loading: loading.models.sysUser,
}))
@Form.create()
export default class ManagersManagement extends Component {
  state = {
    showManagerInfoVisible: false,
    showManagerAddVisible: false,
    id: undefined,
    pageNum: globalConstant.paging.defaultPageNum,
    pageSize: globalConstant.paging.defaultPageSize,
    form: {},
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/fetch',
      payload: {
        pageNum: globalConstant.paging.pageNum,
        pageSize: globalConstant.paging.pageSize,
      },
    });
  }
  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.state.form,
    };
    this.setState({
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    });
    dispatch({
      type: 'sysUser/fetch',
      payload: params,
    });
  }
  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const rangeValue = fieldsValue.date || undefined;
      dispatch({
        type: 'sysUser/fetch',
        payload: {
          crtTimeEnd: rangeValue && rangeValue[1].valueOf(),
          crtTimeStart: rangeValue && rangeValue[0].valueOf(),
          keywordsNames: fieldsValue.select || null,
          keywordsValue: fieldsValue.keywordsValue || null,
          accountStatus: fieldsValue.status || null,
        },
      });
      this.setState({
        form: {
          crtTimeEnd: rangeValue && rangeValue[1].valueOf(),
          crtTimeStart: rangeValue && rangeValue[0].valueOf(),
          keywordsNames: fieldsValue.keywordsNames || null,
          keywordsValue: fieldsValue.keywordsValue || null,
          accountStatus: fieldsValue.status || null,
        },
      });
    });
  }
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      form:{},
    });
    dispatch({
      type: 'sysUser/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
  }
  handleManagerInfoModal = (value) => {
    this.setState({
      showManagerInfoVisible: true,
      id: value,
    });
  };
  handleUpdateStatus = (id, status) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/updateStatus',
      payload: {
        id,
        accountStatus: status,
      },
      callback: () => {
        dispatch({
          type: 'sysUser/fetch',
          payload: {
            pageNum: this.state.pageNum,
            pageSize: this.state.pageSize,
            ...this.state.form,
          },
        });
      },
    });
  };
  handleAddMasterModal= () => {
    this.setState({
      showManagerAddVisible: true,
    });
  }
  handleManagerInfoModalCancel =() => {
    this.setState({
      showManagerInfoVisible: false,
    });
  }
  handleManagerAddModalCancel =(refreshFlag) => {
    if (refreshFlag) {
      this.props.dispatch({
        type: 'sysUser/fetch',
        payload: {
          pageNum: this.state.pageNum,
          pageSize: this.state.pageSize,
          ...this.state.form,
        },
      });
    }
    this.setState({
      showManagerAddVisible: false,
    });
  }
  handleChildModal = (refreshFlag) => {
    if (refreshFlag) {
      this.props.dispatch({
        type: 'sysUser/fetch',
        payload: {
          pageNum: this.state.pageNum,
          pageSize: this.state.pageSize,
          ...this.state.form,
        },
      });
    }
    this.setState({
      showManagerInfoVisible: false,
    });
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字">
              {getFieldDecorator('keywordsValue')(
                <Input placeholder="请输入搜索关键字" />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="创建日期">
              {getFieldDecorator('date')(
                <DatePicker.RangePicker
                  format={globalConstant.dateFormat}
                />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={null}>全部</Option>
                  <Option value={globalConstant.accountStatus.USER_ACCOUNT_STATUS_NORMAL}>
                    使用中
                  </Option>
                  <Option value={globalConstant.accountStatus.USER_ACCOUNT_STATUS_LOCK}>
                    禁用中
                  </Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字类型">
              {getFieldDecorator('select', {
                rules: [
                  {
                    type: 'array',
                  }],
              })(
                <Select
                  mode="multiple"
                >
                  <Select.Option value="name">姓名</Select.Option>
                  <Select.Option value="mobilePhone">手机</Select.Option>
                  <Select.Option value="idcard">身份证</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={16} style={{ textAlign: 'right' }}>
            <span className={styles.submitButtons}>
              <Button icon="search" type="primary" htmlType="submit" >查询</Button>
              <Button icon="reload" style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  render() {
    const { sysUser: { sysUserList }, loading } = this.props;
    console.log('sysUserList', sysUserList);
    const { showManagerAddVisible, showManagerInfoVisible, id } = this.state;
    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        width: '15%',
      },
      {
        title: '姓名',
        dataIndex: 'name',
        width: '15%',
      },

      {
        title: '登录名',
        dataIndex: 'username',
        width: '15%',
      },
      {
        title: '手机号码',
        dataIndex: 'mobilePhone',
        width: '15%',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        width: '10%',
      },
      {
        title: '创建时间',
        dataIndex: 'updTime',
        width: '15%',
        render: (text) => {
          return moment(text).format(globalConstant.dateFormat);
        },
      },
      {
        title: '操作',
        key: 'key',
        render: (text) => {
          const menu = (
            <Menu>
              <Menu.Item key="1">
                <Button
                  type={text.accountStatus === 'USER_ACCOUNT_STATUS_NORMAL' ? 'danger' : 'primary'}
                  onClick={() => {
                    this.handleUpdateStatus(text.id, text.accountStatus === 'USER_ACCOUNT_STATUS_NORMAL' ? 'USER_ACCOUNT_STATUS_LOCK' : 'USER_ACCOUNT_STATUS_NORMAL'); }
                  }
                  icon={text.accountStatus === 'USER_ACCOUNT_STATUS_NORMAL' ? 'close' : 'check'}
                >
                  {text.accountStatus === 'USER_ACCOUNT_STATUS_NORMAL' ? '禁用' : '启用'}
                </Button>
              </Menu.Item>
              <Menu.Item key="2">
                <Button
                  icon="info-circle-o"
                  onClick={() => { this.handleManagerInfoModal(text.id); }}
                >
                  详情
                </Button>
              </Menu.Item>
            </Menu>
          );
          return (
            <Dropdown overlay={menu}>
              <Button style={{ width: 100 }}>
                操作 <Icon type="down" />
              </Button>
            </Dropdown>
          );
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: sysUserList.totals,
      showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
      ...globalConstant.pagingFormat,
    };
    return (
      <PageHeaderLayout title="操作员管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>
            <Card bordered>
              <div className={styles.tableListOperator}>
                <Button icon="plus" type="primary" onClick={() => this.handleAddMasterModal()}>
                  新建
                </Button>
              </div>
              <Table
                bordered
                loading={loading}
                rowKey={record => record.id}
                dataSource={sysUserList && sysUserList.items}
                columns={columns}
                pagination={paginationProps}
                onChange={this.handleStandardTableChange}
              />
            </Card>
          </div>
        </Card>
        <Modal
          visible={showManagerInfoVisible}
          title="查看管理员"
          footer={null}
          width="60%"
          onCancel={() => this.handleManagerInfoModalCancel()}
          destroyOnClose
        >
          <ShowManagerInfo data={id} childModal={this.handleChildModal.bind(this)} />
        </Modal>
        <Modal
          visible={showManagerAddVisible}
          title="添加管理员"
          footer={null}
          width="60%"
          onCancel={() => this.handleManagerAddModalCancel()}
          destroyOnClose
        >
          <AddManager closeModal={this.handleManagerAddModalCancel.bind(this)} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
